<template>
  <div class="zz-imgbox">
    <el-dialog title="选择图片" :visible.sync="visible" top="5vh" width="798px">
      <el-tabs
        v-model="activeTab"
        @tab-click="loadList(1)"
        @tab-remove="delGroup"
        tab-position="left"
        class="zz-imgbox-dialog"
        :closable="true"
      >
        <el-tab-pane
          v-for="item in groupList"
          :key="item.group_id"
          :label="item.group_name"
          :name="item.group_id + ''"
          class="pick-tab"
        >
          <div class="zz-img-list-loading" v-if="isLoading">
            <div class="el-icon-loading"></div>
          </div>
          <div class="zz-main zz-img-list">
            <div class="no-image" v-if="!isLoading && result.total === 0">
              该分组没有图片
            </div>
            <div
              class="img-item"
              v-for="(img, itemIndex) in result.items"
              @click="onClickListImage(img)"
              :key="itemIndex"
            >
              <div class="thumb-wp">
                <img :src="img.thumb" alt="img.name" />
              </div>
              <div class="title">{{ img.name }}</div>
              <div class="label" v-if="img.label">{{ img.label }}</div>
              <span class="selected" v-if="img.selected"
              ><span class="icon el-icon-check"></span
              ></span>
            </div>
          </div>
          <pagination
            style="padding: 0 0"
            layout="total, prev, pager, next"
            :total="result.total"
            :page.sync="queryParam.page"
            :limit.sync="queryParam.limit"
            @pagination="loadList"
          />
          <div class="zz-foot">
            <el-button size="medium" style="float: left" @click="addGroup()">
              添加组
            </el-button>

            <el-select v-model="moveGroupId" @change="annexMove">
              <el-option label="移动图片" :value="-2"></el-option>
              <el-option
                v-for="(v, i) in groupList"
                :key="i"
                :label="v.group_name"
                :value="v.group_id"
                v-show="v.group_id != 0"
              ></el-option>
            </el-select>

            <el-upload
              style="display: inline-block"
              :action="action"
              :headers="headers"
              :multiple="true"
              :data="{ group_id: activeTab }"
              :show-file-list="false"
              :on-success="onUploadSuccess"
            >
              <el-button size="medium"
              >上传图片<i class="el-icon-upload"></i
              ></el-button>
            </el-upload>
            <el-badge :value="images.length" class="item">
              <el-button
                type="primary"
                size="medium"
                :disabled="images.length === 0"
                @click="onConfirm"
              >确定</el-button
              >
            </el-badge>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
  </div>
</template>

<script type="text/babel">
import store from "@/store";
import request from "@/utils/request";
import { Message } from "element-ui";

export default {
  name: "ZzImgManager",

  model: {
    prop: "images",
    event: "change",
  },

  data() {
    return {
      images: [], // 已选图片

      listUrl: "admin/annex-list", // 图片列表数据URL
      groupUrl: "admin/annex-group", // 图片组请求地址
      annexMoveUrl: "admin/annex-move", // 图片移动

      action: "", // 图片上传URL
      headers: {}, // 设置上传的请求头部

      moveGroupId: -2,

      activeTab: "0",

      options: {
        multiple: false, // 是否支持选取多个图片
        limit: 10, // 最多可选择图片数量
        callback: null,
      },

      isLoading: true,
      visible: false,
      uploadSuccessCount: 0,

      result: {
        items: [],
        total: 0,
      },

      queryParam: {
        page: 1,
        limit: 15,
        group_id: 0,
      },

      groupList: [],
    };
  },
  created() {
    this.action = process.env.VUE_APP_BASE_API + "/admin/annex-upload";
    this.headers["Authorization"] = "Bearer " + store.getters.token;
    this.loadGroupList();
  },
  methods: {
    setOptions(options) {
      Object.assign(this.options, options);
    },

    show() {
      this.visible = true;
    },

    hide() {
      this.visible = false;
    },

    onConfirm() {
      this.hide();
      if (typeof this.options.callback === "function") {
        this.options.callback(this.images);
      }
    },

    annexMove(val) {
      if (this.images.length < 1) {
        Message.error("请选择需要移动的图片");
        this.moveGroupId = -2;
        return false;
      }
      let _this = this;
      let tabs = this.groupList;
      let tab = tabs.filter((tab) => tab.group_id == val + "");
      let ids = [];
      this.images.forEach((vv) => {
        ids.push(vv.id);
      });
      this.$confirm("移动到" + tab[0].group_name, "提示", {})
        .then(() => {
          request
            .post(this.annexMoveUrl, { group_id: val, ids: ids })
            .then((res) => {
              console.log(res);
              if (res.code == 1) {
                Message.success("移动成功");
                _this.activeTab = val + "";
                _this.clearListSelected();
                _this.images = [];
                _this.moveGroupId = -2;
                _this.loadList();
              }
            })
            .catch((err) => {
              console.log(err);
            });
        })
        .catch(() => {});
    },

    addGroup() {
      this.$prompt("请输入分组名称", "提示", {})
        .then(({ value }) => {
          request
            .post(this.groupUrl, { group_name: value })
            .then((res) => {
              console.log(res);
              let data = res.data;
              Message.success("添加成功");
              if (res.code == 1) {
                this.groupList.push(data);
              }
            })
            .catch((err) => {
              console.log(err);
            });
        })
        .catch(() => {});
    },

    delGroup(targetName) {
      if (targetName == -1 || targetName == 0) {
        Message.error("不可删除");
        return false;
      }
      let tabs = this.groupList;
      console.log(tabs);
      let activeName = this.activeTab;
      let _this = this;
      this.$confirm("确认删除？", "提示", {
        type: "warning",
      })
        .then(() => {
          request
            .delete(_this.groupUrl + '/' + targetName)
            .then((res) => {
              console.log(res);
              if (res.code == 1) {
                Message.success("删除成功");
                if (activeName == targetName) {
                  tabs.forEach((tab, index) => {
                    if (tab.group_id == targetName) {
                      let nextTab = tabs[index + 1] || tabs[index - 1];
                      if (nextTab) {
                        activeName = nextTab.group_id;
                        _this.activeTab = activeName + "";
                        _this.loadList();
                      }
                    }
                  });
                }
                _this.activeTab = activeName + "";
                _this.groupList = tabs.filter(
                  (tab) => tab.group_id != targetName + ""
                );
              }
            })
            .catch((err) => {
              console.log(err);
            });
        })
        .catch(() => {});
    },

    /**
     * 点击图片时选中或取消选中图片
     * @param img object
     */
    onClickListImage(img) {
      console.log(typeof this.images);
      if (typeof this.images == "string") {
        this.images = [];
      }
      var imgIndex = this.selectedImageIndex(img);
      if (imgIndex >= 0) {
        // 取消图片已选状态
        img.selected = false;
        this.images.splice(imgIndex, 1);
        return;
      }

      if (!this.options.multiple) {
        // 单选时，先取消已选
        this.images = [];
        this.clearListSelected();
      }

      // 选择图片
      if (this.options.multiple && this.images.length >= this.options.limit) {
        Message.warning("图片最多选择" + this.options.limit + "张");
        return;
      }

      img.selected = true;
      this.images.push(JSON.parse(JSON.stringify(img)));
    },

    clearListSelected(img) {
      for (let i = 0; i < this.result.items.length; i++) {
        if (img) {
          if (img.url === this.result.items[i].url) {
            this.result.items[i].selected = false;
            break;
          }
        } else if (this.result.items[i].selected) {
          this.result.items[i].selected = false;
        }
      }
    },

    /**
     * 获取组
     */
    loadGroupList() {
      let _this = this;
      request
        .get(this.groupUrl)
        .then((res) => {
          let data = res.data;
          data.unshift(
            { group_id: 0, group_name: "全部" },
            { group_id: -1, group_name: "未分组" }
          );
          _this.groupList = data;
        })
        .catch((err) => {
          console.log(err);
        });
    },

    /**
     * 加载图片列表数据
     * @param {int} page
     */
    loadList() {
      if (!this.listUrl) {
        throw new Error("listUrl is required");
      }
      this.isLoading = true;
      this.queryParam.group_id = this.activeTab;
      request
        .get(this.listUrl, this.queryParam)
        .then((res) => {
          console.log(res);
          const result = res.data;
          this.result.total = parseInt(result.total);

          let imageList = [];
          let listCount = 0;

          for (let i = 0; i < result.items.length; i++) {
            listCount++;

            // 每页只显示15条
            if (listCount > 15) {
              break;
            }

            let img = result.items[i];

            if (!img.thumb) {
              img.thumb =
                img.url + "?imageView2/1/w/180/h/180/format/jpg/q/100";
            }

            // 图片名
            if (!img.name) {
              img.name = img.url.substr(img.url.lastIndexOf("/") + 1);
            }

            // 图片其他信息
            if (typeof img.label === "undefined") {
              img.label = "";
            }

            // 图片选中状态
            img.selected = this.selectedImageIndex(img) > -1;

            imageList.push(img);
          }
          console.log("imageListi", imageList);

          this.result.items = imageList;
          this.isLoading = false;
        })
        .catch((err) => {
          console.log(err);
        });
    },

    /**
     * 图片已选则返回下标，未选则返回-1
     */
    selectedImageIndex(img) {
      for (let i = 0; i < this.images.length; i++) {
        const selectedImg = this.images[i];

        if (selectedImg.url === img.url) {
          return i;
        }
      }

      return -1;
    },

    /**
     * 分页页面变化时刷新数据
     * @param page
     */
    onPageNumChange(page) {
      this.loadList(page);
    },

    /**
     * 上传成功处理
     * @param response
     * @param file
     * @param fileList
     * @returns {boolean}
     */
    onUploadSuccess(response, file, fileList) {
      if (response.errMsg) {
        Message.error(response.errMsg || "上传失败");
        return false;
      }

      let img = response.data;

      if (!img.thumb) {
        img.thumb = img.url + "?imageView2/1/w/180/h/180/format/jpg/q/100";
      }

      this.result.items.unshift(img);

      if (this.result.items > 15) {
        this.result.items.pop();
      }

      this.result.total += 1;
    },

    onRemove(imgIndex, img) {
      this.images.splice(imgIndex, 1);
      this.clearListSelected(img);
    },
  },

  mounted() {
    this.loadList();
  },

  computed: {},
};
</script>

<style lang="scss">
.zz-images {
  .el-upload-list__item {
    width: 78px;
    height: 78px;
    line-height: 82px;
    border-radius: 5px;
  }
}

.no-image {
  line-height: 120px;
  text-align: center;
  color: #999;
}

.zz-imgbox-dialog {
  $bg: #f6f6f6;

  .el-badge {
    vertical-align: bottom;
  }

  .el-dialog {
    width: 720px;

    .el-dialog__header {
      border-bottom: 1px solid #e8e8e8;
    }

    .el-dialog__body {
      padding: 0;
      background: $bg;
    }
  }

  .el-tabs {
    .el-tabs__header {
      width: 100px;
      margin-right: 0;
      margin-top: 5px;
      .el-tabs__nav-wrap::after {
        background: $bg;
      }
    }
    .el-tabs__item.is-active {
      background: #fff;
    }
    .el-tabs--left .el-tabs__nav-wrap {
      padding-top: 15px;
    }

    .el-tabs__content {
      height: 494px;
      background: #fff;
    }
  }

  .zz-foot {
    padding: 20px 20px 0 20px;
    text-align: right;
    .el-button {
      margin: 0 0 0 10px;
    }
  }

  .pick-tab {
    min-height: 500px;
    position: relative;

    .zz-img-list-loading {
      position: absolute;
      z-index: 9;
      left: 0;
      right: 0;
      width: 100%;
      height: 360px;
      background: #fff;
      text-align: center;

      .el-icon-loading {
        font-size: 50px;
        color: #409eff;
        line-height: 250px;
      }
    }

    .zz-img-list {
      padding: 10px;
      height: 360px;

      .img-item {
        $imgSize: 100px;
        float: left;
        margin: 10px;
        width: $imgSize;
        cursor: pointer;
        position: relative;
        font-size: 12px;

        img {
          width: $imgSize;
          height: $imgSize;
          display: block;
        }

        .title {
          line-height: 24px;
          height: 24px;
          display: block;
          overflow: hidden;
          background: $bg;
          padding: 0 5px;
          display: none;
        }

        .label {
          position: absolute;
          z-index: 9;
          left: 0;
          bottom: 24px;
          width: 100%;
          height: 21px;
          line-height: 21px;
          text-align: center;
          color: #fff;

          &:after {
            content: " ";
            position: absolute;
            left: 0;
            bottom: 0;
            width: 100%;
            height: 21px;
            background: #000;
            opacity: 0.3;
            z-index: -1;
          }
        }

        .selected {
          position: absolute;
          right: 0px;
          top: 0px;
          width: 100%;
          height: 100%;
          border: 3px solid #409eff;
          border-radius: 3px;
          text-align: right;
          .icon {
            background: #409eff;
            text-align: center;
            height: 24px;
            width: 24px;
            line-height: 24px;
            display: inline-block;
            font-size: 16px;
            color: #fff;
            border-radius: 0 0 0 3px;
            position: absolute;
            right: 0;
            top: 0;
          }
        }
      }

      &::after {
        content: " ";
        display: table;
        height: 0;
        clear: both;
        visibility: hidden;
      }
    }

    .el-pagination {
      background: #f9f9f9;
      position: relative;
      padding: 5px;
      margin: 0 20px 0 20px;
      text-align: right;
      float: none;
      white-space: normal;

      * {
        background: none;
      }
    }
  }
}

.el-upload-list__item-actions {
  a {
    i {
      color: #fff;
    }
  }
}
</style>
